#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

class SafeFile
{
public:
    //在构造函数中初始化资源(托管资源)
    SafeFile(FILE *fp)
    : _fp(fp)
    {
        cout << "SafeFile(FILE *)" << endl;
    }

    //提供若干访问资源的方法（对文件进行写操作）
    //用C的方法向文件中写数据
    void write(const string &msg)
    {
        fwrite(msg.c_str(), 1, msg.size(), _fp);
    }

    //在析构函数中释放资源
    ~SafeFile()
    {
        cout << "~SafeFile()" << endl;
        if(_fp)
        {
            fclose(_fp);
            cout << "fclose(_fp)" << endl;
        }
    }

private:
    FILE *_fp;
};

void test()
{
    string msg = "hello,world\n";
    SafeFile sf(fopen("wd.txt", "a+"));//sf是栈对象
    sf.write(msg);
}

int main(int argc, char **argv)
{
    test();
    return 0;
}

